// import axios from 'axios'
import store from "../store/index.js";
import router from "../router/index";
import { Notify } from "quasar";
const notify = (msg) =>
  Notify.create({
    message: msg,
    position: "top",
    color: "negative",
  });
import { LoadingBar } from "quasar";

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: "/api/v1", //process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 60000,
});

const getCookie = (name) => {
  var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
  return r ? r[1] : undefined;
};

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (config.url.indexOf("/bms/upgrade/") >= 0) {
      delete config.timeout;
    }
    if (store.getters.token) {
      if (
        localStorage.getItem("euworkShop_wechatPathTo_path") != null &&
        localStorage.getItem("euworkShop_wechatPathTo_path")
      ) {
        config.headers.Authorization = localStorage.getItem(
          "token_key_GFYW"
        );
      } else {
        config.headers.Authorization =
          "cyberauth" +
          " " +
          localStorage.getItem("token_key_GFYW") +
          " " +
          "jwt";
      }
      config.headers.db = localStorage.getItem("db_GFYW");
      config.headers["X-CSRFToken"] = getCookie("csrftoken");
      // if (config.url === '/bms/files/updownload/' || config.url.indexOf('/organizer/points/bg-set/') >= 0) {
      //   config.headers['X-CSRFToken'] = getCookie('csrftoken')
      // }
    }

    let data = store.state.leftChart.overPath;
    if (data.overUrl != "") {
      config.baseURL = data.overUrl;
      if (data.overTimeType == "s") {
        config.timeout = parseInt(data.overTime * 1000);
      } else if (data.overTimeType == "m") {
        config.timeout = parseInt(data.overTime * 1000 * 60);
      } else if (data.overTimeType == "h") {
        config.timeout = parseInt(data.overTime * 1000 * 60 * 60);
      } else if (data.overTimeType == "d") {
        config.timeout = parseInt(data.overTime * 1000 * 60 * 60 * 24);
      }
      data.HeaderOne.map((item) => {
        if (item.key != "" && item.value != "") {
          config.headers[item.key] = item.value;
        }
      });
    } else {
      config.baseURL = "/api/v1";
      config.timeout = 60000;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (response.status === 200) {
      if (res.status === 200) {
        return res;
      }
    }
    return response;
  },
  (error) => {
    if (!error.response) {
      // 1、没有token
      notify(error.message);
      if (router.currentRoute._rawValue.path !== "/login") {
        store()
          .dispatch("login/logoutFun")
          .then((_) => {
            router.push({ path: "/login", query: "12345" });
          });
        store().commit("app/SET_VISITED_VIEWS"); //  清空可见tab标签
      }
    } else {
      // token 过期 或 失效 localStorage.getItem('exp_GFYW')
      const tokenEXP = localStorage.getItem("exp_GFYW");
      const currentDate = Date.parse(new Date()).toString().slice(0, 10);
      // console.log(localStorage.getItem('exp_GFYW'), '----------- token设置的过期时间 ----------')
      // console.log(currentDate, '----------- 当前系统时间 ----------')
      if (tokenEXP && currentDate >= tokenEXP) {
        store()
          .dispatch("login/logoutFun")
          .then(() => {
            router.push({ path: "/login" });
            notify("login timeout. Please login again");
          });
        store().commit("app/SET_VISITED_VIEWS"); //  清空可见tab标签
      } else {
        if (
          error.response.data.detail &&
          error.response.data.detail === "非法用户"
        ) {
          store()
            .dispatch("login/logoutFun")
            .then(() => {
              router.push({ path: "/login" });
              notify(error.response.data);
            });
          store().commit("app/SET_VISITED_VIEWS"); //  清空可见tab标签
          return;
        }
        if (error.response.config.url !== "/bms/upgrade/") {
          notify(Object.values(error.response.data)[0]);
        }
      }
    }
    return Promise.reject(error);
  }
);

LoadingBar.setDefaults({
  color: "light-blue-4",
  size: "4px",
  position: "top",
});

export default service;
